<?php
class UnionController extends AdminBaseController {
	public function _initialize() {
		parent::_initialize();
		$this->db = model('Union');
		libfile('form');
	}
/**
 *	  加盟商家列表
 *	  [Jsen.net] (C)2013-2099 Jason Group Science and technology co., LTD.
 *	  This is NOT a freeware, use is subject to license terms
 *
 *	  http://www.jsen.net
 *	  tel:400-681-9511
 */
	public function index(){
		$keyword = isset($_GET['keyword'])?$_GET['keyword']:'';
		$region = model('region')->where(array('parent_id' => 1))->select();
		$city = model('region')->where(array('parent_id' => $info['province']))->select();
        $district = model('region')->where(array('parent_id' => $info['city']))->select();
		if($_GET["act"]=="excel"){
			$sqlmap = array();
			$order = array();
			//排序
			$_order=isset($_POST['order']) ? ($_POST['order']) : NULL;
			$_sort=isset($_POST['sort']) ? ($_POST['sort']) : NULL;
			if($_order && $_sort){
				$order[$_sort] = $_order;
			}else{
				$order['id'] = 'desc';
			}
			$pagenum=isset($_POST['page']) ? intval($_POST['page']) : 1;
			$rowsnum=isset($_POST['rows']) && (int)($_POST['rows']) != 0 ? intval($_POST['rows']) : PAGE_SIZE;
			$data['total'] = $this->db->where($sqlmap)->count();	//计算总数 
			$field = "a.*,b.area_name as prov_name,c.area_name as city_name,d.area_name as dist_name,f.type_name as hangye";
			$join = " LEFT JOIN `__REGION__` as b ON a.province=b.area_id";
			$join.= " LEFT JOIN `__REGION__` as c ON a.city=c.area_id";
			$join.= " LEFT JOIN `__REGION__` as d ON a.district=d.area_id";	
			$join.= " LEFT JOIN `__UNION_TYPE__` as f ON a.fenlei=f.id";	
			
			if($_GET["province"]!="" and $_GET["province"]>0){
				$sqlmap['_string'] = "(a.province='{$_GET[province]}')";
			}
			if($_GET["city"]!="" and $_GET["city"]>0){
				$sqlmap['_string'] = "(a.city='{$_GET[city]}')";
			}
			if($_GET["district"]!="" and $_GET["district"]>0){
				$sqlmap['_string'] = "(a.district='{$_GET[district]}')";
			}
			
			if (isset($keyword) && $keyword) {
				if($sqlmap['_string']==""){
$sqlmap['_string'] = "a.realname LIKE '%{$keyword}%' OR a.phone LIKE '%{$keyword}%' OR a.company_name LIKE '%{$keyword}%'";
				}else{

$sqlmap['_string'] .= " and (a.realname LIKE '%{$keyword}%' OR a.phone LIKE '%{$keyword}%' OR a.company_name LIKE '%{$keyword}%')";
				}
			}
			$data['rows'] = model('Union a')->field($field)->join($join)->where($sqlmap)->order($order);
			
			$headerArr = array('company_name'=>'商店名称 ',
				'realname'=>'联系人',
				'phone'=>'联系电话',
				'address'=>'商店地址',
				'business'=>'经营范围',
				'hangye'=>'行业分类',
				'add_time'=>'更新时间',
			);
			unset($order_sqlmap);
			$this->DownloadCSV2( $data['rows'], $headerArr,$_GET);
			exit;
		}
		if(IS_POST){
			$sqlmap = array();
			$order = array();
			//排序
			$_order=isset($_POST['order']) ? ($_POST['order']) : NULL;
			$_sort=isset($_POST['sort']) ? ($_POST['sort']) : NULL;
			if($_order && $_sort){
				$order[$_sort] = $_order;
			}else{
				$order['id'] = 'desc';
			}
			$pagenum=isset($_POST['page']) ? intval($_POST['page']) : 1;
			$rowsnum=isset($_POST['rows']) && (int)($_POST['rows']) != 0 ? intval($_POST['rows']) : PAGE_SIZE;
			
			$field = "a.*,b.area_name as prov_name,c.area_name as city_name,d.area_name as dist_name,f.type_name as hangye";
			$join = " LEFT JOIN `__REGION__` as b ON a.province=b.area_id";
			$join.= " LEFT JOIN `__REGION__` as c ON a.city=c.area_id";
			$join.= " LEFT JOIN `__REGION__` as d ON a.district=d.area_id";	
			$join.= " LEFT JOIN `__UNION_TYPE__` as f ON a.fenlei=f.id";	
			
			if($_GET["province"]!="" and $_GET["province"]>0){
				$sqlmap['_string'] = "(a.province='{$_GET[province]}')";
			}
			if($_GET["city"]!="" and $_GET["city"]>0){
				$sqlmap['_string'] = "(a.city='{$_GET[city]}')";
			}
			if($_GET["district"]!="" and $_GET["district"]>0){
				$sqlmap['_string'] = "(a.district='{$_GET[district]}')";
			}
			
			if (isset($keyword) && $keyword) {
				if($sqlmap['_string']==""){
$sqlmap['_string'] = "a.realname LIKE '%{$keyword}%' OR a.phone LIKE '%{$keyword}%' OR a.company_name LIKE '%{$keyword}%'";
				}else{

$sqlmap['_string'] .= " and (a.realname LIKE '%{$keyword}%' OR a.phone LIKE '%{$keyword}%' OR a.company_name LIKE '%{$keyword}%')";
				}
				
			}
			$data['total'] =model('Union a')->where($sqlmap)->count();	//计算总数 
			$data['rows'] = model('Union a')->field($field)->join($join)->where($sqlmap)->limit(($pagenum-1)*$rowsnum.','.$rowsnum)->order($order)->select();
			foreach ($data['rows'] as $key => $value) {
				$data['rows'][$key]['address'] = $value["prov_name"].$value["city_name"].$value["dist_name"].$value["address"];
			}
			if (!$data['rows']) $data['rows']=array();
			echo json_encode($data);
		}else{
			include $this->admin_tpl('Union/index');
		}
	}
	/*
	* 通用方法
	* 导出大数据为CSV 
	* 参数依次传入 查询对象,CSV文件列头(键是数据表中的列名,值是csv的列名),文件名.对数据二次处理的函数;
	*/
	private function DownloadCSV2($selectObject,$head,$_GET){
		$fileName=time();
		if ( !is_object( $selectObject ) || !is_array( $head ) ) {
			exit('参数错误!');

		}
		set_time_limit(0);
		//下载头.
		header ('Content-Type: application/vnd.ms-excel;charset=gbk');
		header ('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
		header ('Cache-Control: max-age=0');
		//输出流;
		$file = 'php://output';
		$fp = fopen ( $file, 'a' );

		function changCode( $changArr ) {
			// 破Excel2003中文只支持GBK编码;
			foreach ( $changArr as $k => $v ) {
				$changArr [$k] = iconv ( 'utf-8', 'gbk', $v );
			}
			//返回一个 索引数组;
			return array_values( $changArr );
		};
		//写入头部;
		fputcsv ( $fp, changCode( $head ) );

		//写入数据;
		$pageSize = 100;//每次查询一百条;
		$page  = 1;//起始页码;
		$list = array();
		//查库;
		$cloneObj = clone $selectObject;//因为thinkphp内部执行完select方法后会清空对象属性,所以clone;
		
		$region_arr = model('region')->select();
		foreach($region_arr as $key =>$val){
			$region_arr_info[$val["area_id"]]=$val["area_name"];		
		}
		$is=0;
		while ( $list = $cloneObj ->limit( $pageSize*( ($page++)-1 ), $pageSize )->select()  ) {
			$cloneObj = clone $selectObject;
			//对查询结果二次处理
			foreach ( $list as $key => $value ) {
				$is+=1;
				if($is>2000){
					return;
				}
				$value['address'] =$value["prov_name"].$value["city_name"].$value["dist_name"].$value["address"];
				$diqu = explode("|",$value["quyu"]);
				$str="";
					foreach($diqu as $k=>$val){
						if($val!=""){
							$diqu_info = explode(",",$val);
							if($diqu_info[0]!=""){	
								$str.=$region_arr_info[$diqu_info[0]]."-".$region_arr_info[$diqu_info[1]]."-".$region_arr_info[$diqu_info[2]].";";
							}
						}
					}
				$value['quyu']=$str;
				$value['add_time']= date('Y-m-d H:i',$value['add_time']); 
				$value = array_intersect_key( $value, $head );//返回需要写入CSV的数据;
				$value = array_merge( $head, $value );//利用此函数返回需要的顺序;
				$value = changCode( $value );
				fputcsv ( $fp, $value );//写入数据;
				flush();
			}
			ob_flush();
		}
		exit();
	}
	public function add(){
		$opt = I("opt");
		$id = I("id", 0);
		$validform = TRUE;
		$dialog = TRUE;
		$union_type = m('union_type')->select();
		$region = model('region')->where(array('parent_id' => 1))->select();
        $city = model('region')->where(array('parent_id' => $info['province']))->select();
        $district = model('region')->where(array('parent_id' => $info['city']))->select();
		if($opt=="")$opt="add";
		if (IS_POST) {
			self::save();
		} else {
			if (isset($opt) && $opt) {
				//删除
				if ($opt == 'del' && $id) {
					unset($where);
					$where['id'] = array('in', $id);
					$this->db->where($where)->delete();
					showmessage('恭喜你，删除成功！', U('ArticleAnnounce/lists'), 1);
					exit();
				}
				//添加
				if ($opt == 'add'){
					include $this->admin_tpl('Union/add');
					exit;
				}
				//编辑
				if ($opt == 'edit' && $id > 0) {
					$info = $this->db->where('id=' . $id)->find();
					$city = model('region')->where(array('parent_id' => $info['province']))->select();
        			$district = model('region')->where(array('parent_id' => $info['city']))->select();
					$this->info = $info;
					include $this->admin_tpl('Union/add');
				}
				//修改状态
				if ($opt == 'ajax_status' && $id) {
					unset($where);
					$data['status'] = array('exp', ' 1-status ');
					$this->db->where('id=' . $id)->save($data);
					showmessage('恭喜你，成功改变状态！', U('ArticleAnnounce/lists'), 1);
					exit();
				}
			} else {
				showmessage('参数错误,请联系管理员!');
			}
		}
		exit;
		if(IS_POST){
			$union=$this->db;
			foreach($_POST as $key=>$val){
				$data[$key]=$_POST[$key];	
			}
			$data["status"]=1;
			$data["add_time"]=time();
			$res=$union->add($data);
			if($res>0){
				showmessage('添加商户成功',U('index'),1);
			}else{
				showmessage('添加商户失败',null,0);	
			}	
		}else{
			include $this->admin_tpl('Union/add');
		}
	}
	protected function save() {
		$id = I('id');
		//处理
		if (isset($id) && $id) {
			if ($this->db->create()) {
				$img_list=getImgs($_POST["content"]);
				$this->db->union_img = serialize($img_list);
				$this->db->save();
				$nid = $id;
				showmessage("修改商户成功", U('union/index'),1);
			} else {
				$this->error($this->db->getError());
			}
		} else {
			if ($this->db->create()) {
				$img_list=getImgs($_POST["content"]);
				$this->db->union_img = serialize($img_list);
				$nid = $this->db->add();
				showmessage("添加商户成功", U('union/index'),1);
			} else {
				showmessage($this->db->getError());
			}
		}
	}
	
	
	 public function getArea() {
        $where['parent_id'] = $_GET['areaId'];
        $area = M('region')->where($where)->select();
        $this->ajaxReturn($area);
    }
	/**
	 * 状态修改
	 * @author nbnat.com
	 */
	public function changeStatus($method=null){
		if ( empty($_GET['id']) ) {
		  showmessage('请选择要操作的数据!');
		} 
		$id=$_GET['id'];
		$method = $_GET['method'];
		$db=$this->db;
		switch ( strtolower($method) ){
			case '1':
				$data['status']=0;
				$db->where('id='.$id)->save($data);
			  showmessage('成功处理',null,1);
				break;
			case '0':
				$data['status']=1;
				$db->where('id='.$id)->save($data);
			  showmessage('成功处理',null,1);
				break;
			default:
			  showmessage($method.'参数非法');
		}
	}
	public function getAgency() {
        $area = M('agency')->field("id,realname")->where("district=".$_GET['areaId']." or quyu like '%".$_GET['areaId']."%'")->select();
        $this->ajaxReturn($area);
    }


    public function type(){
		
		if(IS_POST){
			$pagenum=isset($_POST['page']) ? intval($_POST['page']) : 1;
			$rowsnum=isset($_POST['rows']) && (int)($_POST['rows']) != 0 ? intval($_POST['rows']) : PAGE_SIZE;
			$sqlmap = array();
			$order = array();
			$data['rows'] = model('Union_type')->select();
			if (!$data['rows']) $data['rows']=array();
			echo json_encode($data);
		}else{
			include $this->admin_tpl('Union/type');
		}
	}	

	public function typeadd(){
		$opt = I("opt");
		$id = I("id", 0);
		$validform = TRUE;
		$dialog = TRUE;
		if($opt=="")$opt="add";
		if (IS_POST) {
			self::typesave();
		} else {
			if (isset($opt) && $opt) {
				//删除
				if ($opt == 'del' && $id) {
					unset($where);
					$where['id'] = array('in', $id);
					model('Union_type')->where($where)->delete();
					showmessage('恭喜你，删除成功！', U('ArticleAnnounce/lists'), 1);
					exit();
				}
				//添加
				if ($opt == 'add'){
					include $this->admin_tpl('Union/typeadd');
					exit;
				}
				//编辑
				if ($opt == 'edit' && $id > 0) {
					$info = model('Union_type')->where('id=' . $id)->find();
	
					$this->info = $info;
					include $this->admin_tpl('Union/typeadd');
				}
				
			} else {
				showmessage('参数错误,请联系管理员!');
			}
		}
		exit;
		if(IS_POST){
			$union=model('Union_type');
			foreach($_POST as $key=>$val){
				$data[$key]=$_POST[$key];	
			}
			$res=model('Union_type')->add($data);
			if($res>0){
				showmessage('添加成功',U('index'),1);
			}else{
				showmessage('添加失败',null,0);	
			}	
		}else{
			include $this->admin_tpl('Union/typeadd');
		}
	}
	protected function typesave() {
		$id = I('id');
		//处理
		if (isset($id) && $id) {
			if (model('Union_type')->create()) {
				model('Union_type')->save();
				$nid = $id;
				showmessage("修改成功", U('ArticleAnnounce/lists'));
			} else {
				$this->error(model('Union_type')->getError());
			}
		} else {
			if (model('Union_type')->create()) {
				$nid = model('Union_type')->add();
				showmessage("添加成功", U('ArticleAnnounce/lists'));
			} else {
				showmessage(model('Union_type')->getError());
			}
		}
	}
}	
